using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Specialized;
using Microsoft.SharePoint.Utilities;

namespace TST.SharePoint.Shared
{
    public class TSTRedirect : UnsecuredLayoutsPageBase 
    {
        private NameValueCollection _queryString;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            ReDirect();
        }

        private string GetParam(string key)
        {
            if (_queryString == null)
            {
                _queryString = base.Request.QueryString;
            }
            return _queryString[key];
        }



        private void ReDirect()
        {
            string url = null;
            string goTo = GetParam("GoTo");
            if (!string.IsNullOrEmpty(goTo))
            {
                url = System.Web.HttpUtility.UrlDecode(goTo).Trim();
                if (url.ToLower().EndsWith("?id="))
                    url = url.Substring(0, url.Length - 4);
            }
            else
            {
                string siteId = GetParam("SiteId");
                if (string.IsNullOrEmpty(siteId))
                {
                    throw new Exception("Parameter SiteId cannot be found.");
                }
                string webId = GetParam("WebId");
                string listId = GetParam("ListId");
                using (SPSite site = new SPSite(new Guid(siteId)))
                {
                    if (string.IsNullOrEmpty(webId))
                    {
                        url = site.Url;
                    }
                    else
                    {
                        using (SPWeb web = site.OpenWeb(new Guid(webId)))
                        {
                            if (string.IsNullOrEmpty(listId))
                            {
                                url = web.Url;
                            }
                            else
                            {
                                SPList list = web.Lists[new Guid(listId)];
                                url = list.DefaultViewUrl;
                            }
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(url))
                SPUtility.Redirect(url, SPRedirectFlags.Static, this.Context);
        }
    }
}
